package com.baimo.controller;

import com.alibaba.fastjson.JSON;
import com.baimo.pojo.FriendLink;
import com.baimo.pojo.Message;
import com.baimo.service.FriendLinkService;
import com.baimo.tool.IPUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author 白墨
 * @ClassName ShowFriendLinkController.java
 * @Description 友情链接客户控制层
 * @createTime 2021/4/24 23:06:54
 */
@Controller
public class FriendShowLinkController {
    /**redis状态*/
    private static String STATE="succeed";
//    @Resource
    @Autowired
    private FriendLinkService friendLinkService;
//    @Resource
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @description 申请友情链接
     * @author 白墨
     * @param friendLink 友情链接实体类
     * @param request 请求
     * @updateTime 2021/4/28 3:37:29
     * @return java.lang.String
     */
    @PostMapping("/friends")
    @ResponseBody
    public String post(FriendLink friendLink,HttpServletRequest request) {
        String ipAddr = IPUtils.getIpAddr(request);
        String state = stringRedisTemplate.opsForValue().get(ipAddr);
        Message message=null;
        if (!FriendShowLinkController.STATE.equals(state)){
            if (friendLink.getName() != null && friendLink.getEmail() != null && friendLink.getNickname() != null && friendLink.getUrl() != null
                    && friendLink.getName().length()>0 && friendLink.getEmail().length()>0 && friendLink.getNickname().length()>0 && friendLink.getUrl().length()>0
            ) {
                Integer i =  friendLinkService.addFriendLink(friendLink);
                if (i >0 ) {
                    //放入redis，设置有效期，1，天
                    stringRedisTemplate.opsForValue().set(ipAddr,"succeed",1L, TimeUnit.DAYS);
                    message=new Message(200,"positive","申请成功，我们将会在三日内给您发送结果邮件。");
                } else {
                    stringRedisTemplate.opsForValue().set(ipAddr,"fail",1L, TimeUnit.DAYS);
                    message=new Message(500,"negative","申请的人太多啦，请稍后再试");
                }
            }else {
                message=new Message(500,"negative","申请失败，请填写完整信息。");
            }
        }else {
            message=new Message(500,"negative","您最近一天已经成功申请过友链了，请不要重复申请。");
        }
        return JSON.toJSONString(message);

    }
}
